<?php
/*

  Форм-процессор
  * see http://in.jetstyle.ru/rocket/rocketforms

  FormComponent_model_plain( &$config )
      - $field -- $field->config instance-a поля

  -------------------

  * model       : прямой ввод-вывод в БД

  -------------------

  // Модель. Операции с данными и хранилищем

  * Model_LoadFromArray( $a )
  * Model_ToArray( &$a )

  * Model_DbInsert( &$fields, &$values )
  * Model_DbUpdate( $data_id, &$fields, &$values )
  * Model_DbAfterInsert( $data_id )
  * Model_DbAfterUpdate( $data_id )
  * Model_DbDelete( $data_id )
  * Model_DbLoad( $db_row )

  * Model_SetDefault()

  * Model_ToSession( &$session_storage )
  * Model_FromSession( &$session_storage )

  * Model_GetDataValue()

================================================================== v.0 ( max@ )
*/

$this->UseClass( "Form_FormComponents_model_plain" );

class FormComponent_model_upload extends FormComponent_model_plain
{
   // MODEL ==============================================================================
    var $chmod = 0744;
    var $msg = array("errno" =>
                 array ( 0 => "<i>There is no error, the file uploaded with success.</i>",
                         1 => "<i>The uploaded file exceeds the upload_max_filesize directive in php.ini. </i>",
                         2 => "<i>The uploaded file exceeds the MAX_FILE_SIZE in the html form.</i>",
                         3 => "<i>The uploaded file was only partially uploaded.</i>",
                         4 => "<i>No file was uploaded.</i>",
                       )
                     );

   // ---- работа с хранилищем в массиве ----
   function Model_LoadFromArray( $a )
   {
      /* руками не трогать! никаких данных из поста(=массива) при аплоаде быть не может,
         такая загрузка вытирает загруженное из БД имя файла */
   }


   function Model_DbDelete( $data_id )
   {
     $_file = $_SERVER["DOCUMENT_ROOT"].$this->field->rh->base_url.
              $this->field->config["save_path"].$this->Model_GetDataValue();
     if (file_exists($_file) && is_file($_file)) { chmod($_file, 0777); unlink($_file); }
   }

   function Model_DbInsert( &$fields, &$values )
   {
     // если файл не грузили, NOOP
     if (!$_FILES["_".$this->field->name]['size']) return;

     $this->_HandleUpload();

     // добавить в запрос к БД
     $fields[] = $this->field->name;
     $values[] = $this->name_to;

   }

  function _HandleUpload ()
  {
     // замес :
     $this->file_tmp  = $_FILES["_".$this->field->name]['tmp_name'];
     $this->upload_to = $_SERVER["DOCUMENT_ROOT"] . $this->field->rh->base_url . $this->field->config["save_path"];
     $this->name_to   = $this->_MakeFileName($_FILES["_".$this->field->name]['name']);
     $this->chmod     = $this->field->config["chmod"]?$this->field->config["chmod"]:$this->chmod;
     $this->_Upload();

     // если не загрузили_лося - ахаем. кстати, здорово бы было передавать errorlog валидатору )
     if (!$this->_Upload() || $_FILES["_".$this->field->name]['error'])
         $this->field->rh->debug->Trace(
              $this->msg["errno"][$_FILES["_".$this->field->name]['error']].
              "this->file_tmp:".$this->file_tmp."<br />".
              "this->upload_to:".$this->upload_to."<br />".
              "this->name_to:".$this->name_to."<br />"
        );

  }
  function _MakeFileName ( $filename )
  {
    // фаза 1a : подготовка
    $file_parts = pathinfo($filename);
    $file_w_ext  = $file_parts["basename"];
    $file_ext    = $file_parts["extension"];
    $file_no_ext = substr($file_w_ext, 0, strlen($file_w_ext)-strlen($file_ext));

    // 1b : транслитто
    $this->field->rh->UseLib("typografica", "classes/typografica");
    $name = Translit::Supertag( $file_no_ext, $allow_slashes = false );

    // фаза 2. проверка на существование файла с таким именем в директории
    $_name = $name;
    $c = 1;

    while (file_exists($this->upload_to.$name.".".$file_ext))
    {
      if ($name == $_name) $name = $_name.$c;
      else $name = $_name.(++$c);
    }
    $result = $name.".".$file_ext;

    return $result;
  }

  function _Upload ()
  {
    $a = move_uploaded_file($this->file_tmp, $this->upload_to.$this->name_to);
    chmod($this->upload_to.$this->name_to, $this->chmod);
    return  $a;

  }

// EOC{ FormComponent_model_upload }
}


?>
